<template>
  <div class="flex flex-col flex-center">
    <h3 class="text-center m-0 mb-20px">欢迎登录{{ defaultSettings.title }}</h3>
    <a-form ref="loginFormRef" name="loginForm" :model="loginFormData" :rules="loginRules">
      <a-form-item name="username">
        <a-input v-model:value.trim="loginFormData.username" placeholder="请输入用户名" allow-clear>
          <template #prefix>
            <user-outlined />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item name="password">
        <a-input-password
          v-model:value="loginFormData.password"
          placeholder="请输入密码"
          allow-clear
          @keyup="checkCapsLock"
          @keyup.enter="handleLoginSubmit"
        >
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item name="captchaCode">
        <div class="flex items-center gap-10px">
          <a-input
            class="flex-1"
            @keyup.enter="handleLoginSubmit"
            v-model:value.trim="loginFormData.captchaCode"
            placeholder="请输入验证码"
            allow-clear
          >
            <template #prefix>
              <SafetyCertificateOutlined />
            </template>
          </a-input>
          <div class="cursor-pointer h-40px w-120px flex-center" @click="getCaptcha">
            <div v-if="codeLoading" class="is-loading">
              <LoadingOutlined style="font-size: 20px" />
            </div>
            <img
              v-else-if="captchaBase64"
              border-rd-4px
              object-cover
              :src="captchaBase64"
              alt="captchaCode"
            />
            <a-button class="h-full flex items-center" v-else type="link"> 获取验证码 </a-button>
          </div>
        </div>
      </a-form-item>

      <div class="flex justify-between items-center w-full mb24px">
        <a-checkbox v-model:checked="loginFormData.rememberMe">记住我</a-checkbox>
        <a-button type="link" @click="toOtherForm('resetPwd')"> 忘记密码 </a-button>
      </div>

      <!-- 登录按钮 -->
      <a-form-item>
        <a-button :loading="loading" type="primary" class="w-full" @click="handleLoginSubmit">
          登录
        </a-button>
      </a-form-item>
    </a-form>
    <div class="flex-center gap-10px">
      <div class="text-sm">您没有账号？</div>
      <a-button @click="toOtherForm('register')" type="link">免费注册</a-button>
    </div>

    <!-- 第三方登录 -->
    <div class="third-party-login">
      <div class="divider-container">
        <div class="divider-line"></div>
        <span class="divider-text">其他</span>
        <div class="divider-line"></div>
      </div>
      <div class="flex-center gap-x-5 w-full text-[#909399]">
        <div class="flex-center text-[20px]">
          <WechatOutlined @click="toOtherForm('wechat')" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { AuthStorage } from '@/utils/auth'
import AuthAPI from '@/api/auth-api'
import {
  UserOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  LoadingOutlined,
  WechatOutlined,
} from '@ant-design/icons-vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store'
import { message } from 'ant-design-vue'
import { defaultSettings } from '@/settings.js'

const route = useRoute()
const loginFormRef = ref()
const loading = ref(false)
// 是否大写锁定
const isCapsLock = ref(false)
// 验证码图片Base64字符串
const captchaBase64 = ref()
// 记住我
const rememberMe = AuthStorage.getRememberMe()
const codeLoading = ref(false)
const loginFormData = ref({
  username: 'admin',
  password: '123456',
  captchaKey: '',
  captchaCode: '',
  rememberMe,
})
const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '用户名不能为空',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '密码不能为空',
      },
      {
        min: 6,
        message: '密码长度至少6位',
        trigger: 'blur',
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: 'blur',
        message: '验证码不能为空',
      },
    ],
  }
})

const userStore = useUserStore()

// 检查输入大小写
function checkCapsLock(event) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState('CapsLock')
  }
}

function getCaptcha() {
  codeLoading.value = true
  AuthAPI.getCaptcha()
    .then((data) => {
      loginFormData.value.captchaKey = data.captchaKey
      captchaBase64.value = data.captchaBase64
    })
    .finally(() => (codeLoading.value = false))
}

const handleLoginSubmit = async () => {
  try {
    // 1. 表单验证
    const valid = await loginFormRef.value?.validate()
    if (!valid) return

    loading.value = true

    // 2. 执行登录
    await userStore.login(loginFormData.value)

    message.success("登录成功")
    const redirectPath = route.query.redirect || '/'

    await router.push(decodeURIComponent(redirectPath))
  } catch (error) {
    getCaptcha() // 刷新验证码
  } finally {
    loading.value = false
  }
}

// const emit = defineEmits(['update:modelValue'])
function toOtherForm(type) {
  message.warning('开发中...')
  // emit('update:modelValue', type)
}

onMounted(() => getCaptcha())
</script>
<style lang="scss" scoped>
.third-party-login {
  width: 100%;
  .divider-container {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .divider-line {
      flex: 1;
      height: 1px;
      background: linear-gradient(to right, transparent, #e4e7ed, transparent);
    }

    .divider-text {
      padding: 0 16px;
      font-size: 12px;
      color: #606266;
      white-space: nowrap;
    }
  }
}
</style>
